//app.js
var loginStatus = true;
var config = require('./utils/config')

App({
  onLaunch: function () {
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    var that = this;

    that.globalData.splash_current = 0;

    wx.getSystemInfo({
      success: function (res) {
        that.globalData.screenHeight = res.windowHeight;
        that.globalData.screenWidth = res.windowWidth;
        }
    });

    //获取后台广告（图片）+参数
    //保存到本地
    wx.request({
      url: config.config.splashUrl,
      success: function (res) {
        if (!res.data.status) {
          console.log(res)
          // wx.setStorageSync('splash', null)
        } else {
          that.globalData.splash_url = res.data.url;
          // wx.setStorageSync('splash', res.data.url)
          console.log(res.data.url)
        }
      },
      fail: function (res) {
        console.log(res)
        // wx.setStorageSync('splash', null)
      }
    })    

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // 获取用户信息
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                success: res => {
                  // 可以将 res 发送给后台解码出 unionId
                  this.globalData.userInfo = res.userInfo
                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (this.userInfoReadyCallback) {
                    this.userInfoReadyCallback(res)
                  }
                }
              })
            }
          }
        })
      }
    })
  },
  getUserLoginInfo: function () {
    //调用request请求api转换登录凭证  
    console.log("function app.getUserLoginInfo")    
    var user_openid = wx.getStorageSync('user_openid')
    var user_data = wx.getStorageSync('user_data')
    console.log(user_openid)
    wx.request({
      url: config.config.loginUrl + '?openid='+ user_openid,
      data: user_data,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if(!res.data.status){
          console.log(res)
          wx.setStorageSync('user_type', -1)
        } else{
          wx.setStorageSync('user_type', res.data.type)
          console.log(res.data.type)
        }
      },
      fail: function (res) {
        console.log(res)
        wx.setStorageSync('user_type', -1)
      }
    })
  },  
  getUserOpenID: function (login_code) {
    //调用request请求api转换登录凭证login_code为openid
	var that = this
    console.log("调用request请求api转换登录凭证login_code为openid")
    var user_openid = wx.getStorageSync('user_openid')
    var user_data = wx.getStorageSync('user_data')
    console.log(login_code)
    console.log(user_openid)
    console.log(user_data)
    if (!user_openid){
    //  console.log("应该return")
    //  return
    //}else{
    // var times = setInterval(function () {
      wx.showLoading({
        title: '正在连接服务器，请稍后！',
        mask: true
      }) 
       
      if (user_data) { 
        wx.request({
          url: config.config.getOpenIDUrl + '?js_code=' + login_code,
          data: user_data,
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res)
            wx.setStorageSync('user_openid', res.data.openid)
            that.getUserLoginInfo()
            wx.hideLoading() 
          },fail:function(e){
            console.log(e)
            wx.hideLoading() 
          }
        })
      }else{
        wx.hideLoading() 
        console.log("Userdata Not Ready！")
      }
    }  
  },
  getPromission: function () {
    var that = this
    if (!loginStatus) {
      wx.openSetting({
        success: function (data) {
          if (data) {
            if (data.authSetting["scope.userInfo"] == true) {
              loginStatus = true;
              wx.getUserInfo({
                withCredentials: false,
                success: function (data) {
                  console.info("2成功获取用户返回数据");
                  wx.setStorageSync('user_data', data)
                  console.info(data.userInfo);
                },
                fail: function () {
                  console.info("2授权失败返回数据");
                }
              });
            }
          }
        },
        fail: function () {
          console.info("设置失败返回数据");
        }
      });
    } else {
      wx.login({
        success: function (res) {
          if (res.code) {
            wx.getUserInfo({
              withCredentials: false,
              success: function (data) {
                console.info("1成功获取用户返回数据");
                wx.setStorageSync('user_data', data)
                wx.setStorageSync('login_code', res.code)
                console.info(data.userInfo);
              },
              fail: function () {
                console.info("1授权失败返回数据");
                loginStatus = false;
                // 显示提示弹窗
                wx.showModal({
                  title: '提示标题',
                  content: '提示内容',
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    } else if (res.cancel) {
                      wx.openSetting({
                        success: function (data) {
                          if (data) {
                            if (data.authSetting["scope.userInfo"] == true) {
                              loginStatus = true;
                              wx.getUserInfo({
                                withCredentials: false,
                                success: function (data) {
                                  console.info("3成功获取用户返回数据");
                                  wx.setStorageSync('user_data', data)
                                  // wx.setStorageSync('login_code', data)
                                  console.info(data.userInfo);
                                },
                                fail: function () {
                                  console.info("3授权失败返回数据");
                                }
                              });
                            }
                          }
                        },
                        fail: function () {
                          console.info("设置失败返回数据");
                        }
                      });
                    }
                  }
                });
              }
            });
          }
        },
        fail: function () {
          console.info("登录失败返回数据");
        }
      });
    }
  },
  showModal:function(e){
    wx.showModal({
      title: '提示',
      content: '这是一个模态弹窗',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  showToast: function (e, title, icon, duration){
    console.log(title, icon, duration)
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration
      // title: '加载中',
      // icon: 'loading',
      // duration: 10000
    })

    setTimeout(function () {
      wx.hideToast()
    }, 2000)
  },
  hideToast:function(e){
    wx.hideToast()
  },
  globalData: {
    userInfo: null,
    userOpenID:null,
    keyData:null,
    userInfo: {},
    userType:null,
    hasUserInfo: false,
    register:false,
    role:null,
    location:null,
    screenHeight:null,
    screenWidth:null,
    splash_url:null,
    base:config.config.base,
    splash_current: 0,
  }
})